<template>
  <a-form
    ref="formRef"
    class="form"
    :model="formModel"
    :label-col-props="{ span: 8 }"
    :wrapper-col-props="{ span: 16 }"
    :rules="rules"
  >
    <a-form-item field="loginName" label="登录名">
      <a-input
        v-model="formModel.loginName"
        placeholder="登录名"
        show-word-limit
        allow-clear
        :max-length="30"
      />
    </a-form-item>
    <a-form-item field="userName" label="用户名">
      <a-input
        v-model="formModel.userName"
        placeholder="请输入用户名"
        show-word-limit
        allow-clear
        :max-length="20"
      />
    </a-form-item>
    <a-form-item field="email" label="邮箱">
      <a-input
        v-model="formModel.email"
        placeholder="请输入邮箱"
        allow-clear
      />
    </a-form-item>
    <a-form-item field="phone" label="手机号">
      <a-input
        v-model="formModel.phone"
        placeholder="请输入手机号"
        allow-clear
      />
    </a-form-item>
    <a-form-item field="sex" label="用户性别">
      <a-radio-group v-model="formModel.sex">
        <a-radio value="0">男</a-radio>
        <a-radio value="1">女</a-radio>
      </a-radio-group>
    </a-form-item>
    <a-form-item>
      <a-space>
        <a-button type="primary" :loading="loading" @click="validate">
          {{ $t('userSetting.save') }}
        </a-button>
        <a-button type="secondary" @click="reset">
          {{ $t('userSetting.reset') }}
        </a-button>
      </a-space>
    </a-form-item>
  </a-form>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { useUserStore } from '@/store';
import { updateUserInfo } from '@/api/system/user';
import { FormInstance } from '@arco-design/web-vue/es/form';
import { rules } from '@/views/system/user/config';
import { Message } from '@arco-design/web-vue';

const userStore = useUserStore();

const formRef = ref<FormInstance>();

const loading = ref(false);

const formModel = ref({
  loginName: '',
  userName: '',
  email: '',
  phone: '',
  sex: ''
});

const validate = async () => {
  const valid = await formRef.value?.validate();
  console.log(valid);
  if (!valid) {
    loading.value = true;
    updateUserInfo(formModel.value).then(res => {
      userStore.info();
      Message.success('操作成功');
    }).finally(() => {
      loading.value = false;
    });
  }
};

const reset = async () => {
  await formRef.value?.resetFields();
  formModel.value = {
    loginName: userStore.loginName || '',
    userName: userStore.userName || '',
    email: userStore.email || '',
    phone: userStore.phone || '',
    sex: userStore.sex || ''
  };
};

onMounted(() => {
  formModel.value = {
    loginName: userStore.loginName || '',
    userName: userStore.userName || '',
    email: userStore.email || '',
    phone: userStore.phone || '',
    sex: userStore.sex || ''
  };
});
</script>

<style scoped lang="less">
.form {
  width: 540px;
  margin: 0 auto;
}
</style>
